package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.heima.aliyun.scan.GreenScan;
import com.heima.aliyun.scan.ScanResult;
import com.heima.common.constants.message.PublishArticleConstants;
import com.heima.common.constants.wemedia.WemediaConstants;
import com.heima.common.exception.CustException;
import com.heima.feigns.AdminFeign;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.utils.common.SensitiveWordUtil;
import com.heima.wemedia.service.WmNewsAutoScanService;
import com.heima.wemedia.service.WmNewsService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author mrchen
 * @date 2022/4/28 10:50
 */
@Slf4j
@Service
public class WmNewsAutoScanServiceImpl implements WmNewsAutoScanService {

    @Autowired
    private WmNewsService wmNewsService;

    @Value("${file.oss.web-site}")
    private String website;

    @Autowired
    private AdminFeign adminFeign;

    @Autowired
    private GreenScan greenScan;

    @Autowired
    private RabbitTemplate rabbitTemplate;




    @Override
    public void autoScanWmNews(Integer id) {
        //参数校验
        if (id == null){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"id不能为空");
        }
        //根据id查询文章数据
        WmNews wmNews = wmNewsService.getById(id);
        if (wmNews == null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"文章信息不存在");
        }
        //判断文章状态是否为1
        if (!WemediaConstants.WM_NEWS_SUMMIT_STATUS.equals(wmNews.getStatus())){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW,"不用审核");
        }
        //提取文章中所有的文本内容和图片内容路径
        Map<String,Object> textAndImages = handleTextAndImages(wmNews);
        String content = (String)textAndImages.get("content");
        List<String> images = (List<String>) textAndImages.get("images");

        //进行自管理敏感词校验
        boolean handleSensitive = handleSensitive(content,wmNews);
        if (!handleSensitive){
            log.info("文章里包含敏感词");
            return;
        }
        //进行阿里云内容安全文本检测
        boolean textScan = handleTextScan(content,wmNews);
        if (!handleSensitive){
            log.info("文章里包含敏感词,阿里云文本审核未通过");
            return;
        }
        //进行阿里云内容图片检测
        if (!CollectionUtils.isEmpty(images)) {
            boolean imagesScan = handleImagesScan(images, wmNews);
            if (!imagesScan) {
                log.info("文章里包含不合法图片,阿里云图片审核未通过");
                return;
            }
        }
        //如果全部检测通过，将状态修改为8
        updateWmNews(wmNews,WmNews.Status.SUCCESS.getCode(), "审核通过");

        //通过发送延时消息，进行文章发布上架操作
        //获取发布时间
        long publishTime = wmNews.getPublishTime().getTime();
        //获取当前时间
        long nowTime = System.currentTimeMillis();
        //距离发布时间 = 发布时间 - 当前时间
        long remainTime = publishTime - nowTime;
        //发送消息 并设置消息头 x-delay：距离发布时间
        rabbitTemplate.convertAndSend(PublishArticleConstants.DELAY_DIRECT_EXCHANGE,
                PublishArticleConstants.PUBLISH_ARTICLE_ROUTE_KEY,
                wmNews.getId(),
                new MessagePostProcessor() {
                    @Override
                    public Message postProcessMessage(Message message) throws AmqpException {
                        message.getMessageProperties()
                                .setHeader("x-delay",remainTime<=0?0:remainTime);
                            return message;
                    }
                }
           );
        log.info("成功发送文章待发布消息， 文章id：{} 延迟时间：{}",wmNews.getId(),remainTime);


    }
    //调用阿里云图片审核
    private boolean handleImagesScan(List<String> images, WmNews wmNews) {
        boolean flag = false;
        try {
            ScanResult scanResult = greenScan.imageUrlScan(images);
            String suggestion = scanResult.getSuggestion();
            switch (suggestion) {
                case "block":
                    updateWmNews(wmNews, WmNews.Status.FAIL.getCode(), "图片中包含违规词，审核不通过" + scanResult.getLabel());
                    break;
                case "review":
                    updateWmNews(wmNews, WmNews.Status.ADMIN_AUTH.getCode(), "图片包含不确定因素" + scanResult.getLabel());
                    break;
                case "pass":
                    flag = true;
                    break;
                default:
                    updateWmNews(wmNews, WmNews.Status.ADMIN_AUTH.getCode(), "阿里云审核出现异常，转为人工审核");
                    break;
            }
        }catch (Exception e){
                e.printStackTrace();
                updateWmNews(wmNews, WmNews.Status.ADMIN_AUTH.getCode(), "阿里云审核出现异常，转为人工审核");
            }
        return flag;
        }


    //调用阿里云文本审核
    private boolean handleTextScan(String content, WmNews wmNews) {
        boolean flag = false;
        try {
            ScanResult scanResult = greenScan.greenTextScan(content);
            String suggestion = scanResult.getSuggestion();
            switch (suggestion){
                case "block":
                    updateWmNews(wmNews,WmNews.Status.FAIL.getCode(),"文本中包含违规词，审核不通过" + scanResult.getLabel() );
                    break;
                case "review":
                    updateWmNews(wmNews,WmNews.Status.ADMIN_AUTH.getCode(), "文本包含不确定因素" + scanResult.getLabel());
                    break;
                case "pass":
                    flag = true;
                    break;
                default:
                    updateWmNews(wmNews,WmNews.Status.ADMIN_AUTH.getCode(), "阿里云审核出现异常，转为人工审核");
                    break;
            }
        }catch (Exception e){
            e.printStackTrace();
            updateWmNews(wmNews,WmNews.Status.ADMIN_AUTH.getCode(), "阿里云审核出现异常，转为人工审核");
        }
        return flag;

    }

    //敏感词审核
    private boolean handleSensitive(String content, WmNews wmNews) {
        //基于feign远程查询敏感词列表
        ResponseResult<List<String>> sensitives = adminFeign.sensitives();
        if (!sensitives.checkCode()){
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR);
        }
        List<String> sensitivesDate = sensitives.getData();
        //基于DFA算法，封装数据模型
        SensitiveWordUtil.initMap(sensitivesDate);
        //检测内容是否包含敏感词
        Map<String,Integer> map = SensitiveWordUtil.matchWords(content);
        //如果包含敏感词 将文章状态修改为2
        if (!CollectionUtils.isEmpty(map)) {
           updateWmNews(wmNews,WmNews.Status.FAIL.getCode(), "内容包含敏感词" + map);
            return  false;
        }
        return true;
    }

    private void updateWmNews(WmNews wmNews,Short status,String reason){
        wmNews.setStatus(status);
        wmNews.setReason(reason);
        wmNewsService.updateById(wmNews);
    }


    //抽取文章中所有文本内容和图片内容
    private Map<String, Object> handleTextAndImages(WmNews wmNews) {
        List<Map> contentMap = JSON.parseArray(wmNews.getContent(),Map.class);

        //将所有文本内容拼接成一个字符串
        String content = contentMap.stream()
                .filter(m -> "text".equals(m.get("type")))
                .map(m -> String.valueOf(m.get("value")))
                .collect(Collectors.joining("_hmtt_"));
        content = content + "_hmtt_" + wmNews.getTitle();

        //将所有图片路径收集到一个集合中
        List<String> images = contentMap.stream()
                .filter(m -> "image".equals(m.get("type")))
                .map(m -> String.valueOf(m.get("value")))
                .collect(Collectors.toList());
        if (StringUtils.isNotBlank(wmNews.getImages())){
            List<String> coverImages = Arrays.stream(wmNews.getImages().split(","))
                    .map(url -> website + url)
                    .collect(Collectors.toList());
            images.addAll(coverImages);
        }
        //去除重复的图片
        images = images.stream().distinct().collect(Collectors.toList());
        //将所有内容和路径集合封装到map返回
        Map result = new HashMap();
        result.put("content",content);
        result.put("images",images);
        return result;
    }
}
